package com.moorror.codegenvel.db.sqlite.entity;

import com.moorror.codegenvel.utils.DateUtils;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.compress.utils.Lists;

import java.lang.reflect.Constructor;
import java.util.List;

/**
 * @Author jiyanghuang
 * @Date 2025/8/16 08:52
 */
public abstract class AbEntity implements InfTreeCellEntity{

    private Integer id;

    /**
     * 外键 定义为依附哪个表而存在如：字典data依赖于字典type
     * keyForeign
     */
    protected String kf;

    /**
     * 扩展列Json
     * 不是每个表都有
     */
    protected String extColumnJson;

    /**
     * 是否有变更
     */
    private boolean change = false;

    /**
     * 为啥使用 AbEntity，因为只是子元素，但不一定是这个类的本身
     */
    private List<AbEntity> children;

    private Integer createTime;
    private Integer updateTime;

    public <T extends AbEntity> void addChildren(T ch) {
        if (CollectionUtils.isEmpty(children)) {
            children = Lists.newArrayList();
        }
        children.add(ch);
    }

    /**
     * 针对M对N关系，MN表保存关系数据
     * 将核心数据转换成Json
     * @return
     */
    public String fetchJsonValueNToMN(){
        return "";
    }

    /**
     * 一个表对象一般有唯一的 key
     * @return
     */
    public String uniqueKey(){
        return "";
    }

    /**
     * 填充唯一key
     * @param keyM
     * @param keyN
     */
    public void fillUniqueKeyMN(String keyM, String keyN, String mnJson){

    }

    public static <T extends AbEntity> T of(Class<T> clazz){
        try{
            Constructor<T> constructor = clazz.getConstructor();
            T t = constructor.newInstance();
            Integer currentTime = DateUtils.currentTime();
            t.setCreateTime(currentTime);
            t.setUpdateTime(currentTime);
            return t;
        }catch (Exception ex){
            return null;
        }
    }

    public boolean isChange() {
        return change;
    }

    public void setChange(boolean change) {
        this.change = change;
    }

    public List<AbEntity> getChildren() {
        return children;
    }

    public void setChildren(List<AbEntity> children) {
        this.children = children;
    }

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getKf() {
        return kf;
    }

    public void setKf(String kf) {
        this.kf = kf;
    }

    public String getExtColumnJson() {
        return extColumnJson;
    }

    public void setExtColumnJson(String extColumnJson) {
        this.extColumnJson = extColumnJson;
    }


    public Integer getCreateTime() {
        return createTime;
    }

    public void setCreateTime(Integer createTime) {
        this.createTime = createTime;
    }

    public Integer getUpdateTime() {
        return updateTime;
    }

    public void setUpdateTime(Integer updateTime) {
        this.updateTime = updateTime;
    }
}
